﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Fuse8.ContentManagementFramework.Web.Etc
{
    public class WhiteSpaceFilter : Stream
    {
        private Stream _originalStream;
        private long _position;

        private static Regex _tidyRegex = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}", RegexOptions.Compiled);
        private static Regex _excludeRule = new Regex(@"(<li[ ]class=\""[^>]*whitespaced\"">.*?</li>)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static string _excludeRuleReplacement = "\n\r$1\n\r";

        public WhiteSpaceFilter(Stream stream)
        {
            _originalStream = stream;
        }

        #region Properites

        public override bool CanRead
        {
            get
            {
                return true;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return true;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return true;
            }
        }

        public override void Flush()
        {
            _originalStream.Flush();
        }

        public override long Length
        {
            get
            {
                return 0;
            }
        }

        public override long Position
        {
            get
            {
                return _position;
            }
            set
            {
                _position = value;
            }
        }

        #endregion

        #region Methods

        public override int Read(byte[] buffer, int offset, int count)
        {
            return _originalStream.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return _originalStream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            _originalStream.SetLength(value);
        }

        public override void Close()
        {
            _originalStream.Close();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            byte[] data = new byte[count];

            Buffer.BlockCopy(buffer, offset, data, 0, count);

            string html = Encoding.UTF8.GetString(buffer);

            html = _tidyRegex.Replace(html, string.Empty);

            html = _excludeRule.Replace(html, _excludeRuleReplacement);

            byte[] outdata = Encoding.UTF8.GetBytes(html);

            _originalStream.Write(outdata, 0, outdata.GetLength(0));
        }

        #endregion
    }
}
